﻿using Ruici.BLL;
using Ruici.Web.Services.Model;
using RuiciWebSite.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.DynamicData;
using System.Web.Mvc;

namespace RuiciWebSite.Controllers
{
    public class OrderController : Controller
    {
        private readonly OrderBll _orderBll;
        private readonly DocInfoBll _docInfoBll;
        public static string docImageUrl = ConfigurationManager.AppSettings["ImageUrl"];

        public OrderController()
        {
            _orderBll = new OrderBll();
            _docInfoBll = new DocInfoBll();
        }

        // GET: Order
        public ActionResult Index(string doctorid)
        {
            return View();
        }

        #region Basic Info

        /// <summary>
        /// 获取当前登陆用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetLoginUser(int pid)
        {
            UserInfo userInfo = new UserInfo();
            userInfo.pid = Session["pid"] != null ? int.Parse(Session["pid"].ToString()) : 0;
            userInfo.mobile = Session["mobile"] != null ? Session["mobile"].ToString() : "";
            return Json(userInfo, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取医生信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetDoctorInfo(string id)
        {
            ExpertDetailViewModel doctorinfo = new ExpertDetailViewModel();

            var docinfoget = _docInfoBll.GetDoctor(id);
            doctorinfo.AffiliatedHospital = docinfoget.affiliatedHospital;
            doctorinfo.Id = docinfoget.id;
            doctorinfo.Name = docinfoget.name;
            doctorinfo.OrgId = docinfoget.orgID;
            doctorinfo.DeptName = docinfoget.deptName;
            doctorinfo.DepName2 = docinfoget.depName2;
            doctorinfo.DeptID = docinfoget.deptID;
            doctorinfo.TitleName = docinfoget.titleName;
            doctorinfo.SkillIn = string.IsNullOrWhiteSpace(docinfoget.skillIn) ? "" : docinfoget.skillIn;
            doctorinfo.Image = docImageUrl + docinfoget.image;
            doctorinfo.OrgName = docinfoget.orgName;
            doctorinfo.SkillInText = docinfoget.skillIn;
            doctorinfo.DocInfo = string.IsNullOrWhiteSpace(docinfoget.docInfo) ? "" : docinfoget.docInfo;
            doctorinfo.DocInfoText = docinfoget.docInfo;
            return Json(doctorinfo, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取城市信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetCityList()
        {
            List<CityModel> citylist = new List<CityModel>();
            citylist = _orderBll.GetCityList();
            return Json(citylist, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 获取临床类别信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetClinicCategory(int id)
        {
            var clinicCategory = _orderBll.GetClinicCategory(id);
            return Json(clinicCategory, JsonRequestBehavior.AllowGet); ;
        }

        /// <summary>
        /// 根据城市获取诊所信息
        /// </summary>
        /// <param name="cityId"></param>
        /// <param name="keyword"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetOrganizationList(int cityId, string keyword, int page = 1, int pageSize = 20)
        {
            List<OrganizationModel> organizationList = new List<OrganizationModel>();
            organizationList = _orderBll.GetOrganizationList(keyword, page, pageSize, cityId);
            return Json(organizationList, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取就诊人列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetFamilyMemberList(int pid)
        {
            List<FamilyMemberListModel> organizationList = new List<FamilyMemberListModel>();
            pid = Session["pid"] != null ? int.Parse(Session["pid"].ToString()) : 0;
            //int iPid = 8254006;
            if (pid != 0)
            {
                organizationList = _orderBll.GetFamilyMemberList(pid);
            }
            
            return Json(organizationList, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 增加就诊人
        /// </summary>
        /// <param name="name"></param>
        /// <param name="mobile"></param>
        /// <param name="IdCardNo"></param>
        /// <param name="isDefault"></param>
        /// <param name="relationship"></param>
        /// <param name="familyPid"></param>
        /// <param name="sex"></param>
        /// <param name="address"></param>
        /// <param name="birthday"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult FamilyMemberAdd(string FamilyName, string FamilyMobile, string IDCardNo, bool IsDefault)
        {
            var pid = Session["pid"] != null ? int.Parse(Session["pid"].ToString()) : 0;
            //int iPid = 8254006;
            var returnid = _orderBll.FamilyMemberAdd(pid, FamilyName, FamilyMobile, IDCardNo, IsDefault);
            return Json(returnid, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 修改就诊人（家庭成员）接口
        /// </summary>
        /// <param name="id"></param>
        /// <param name="relationship">就诊人和自己的关系</param>
        /// <param name="name">就诊人姓名</param>
        /// <param name="mobile">就诊人手机号</param>
        /// <param name="address">就诊人住址</param>
        /// <param name="birthday">就诊人生日</param>
        /// <param name="sex">就诊人性别</param>
        /// <param name="IdCardNo">就诊人身份证号码</param>
        /// <param name="isDefault">是否是默认就诊人</param>
        [HttpPost]
        public JsonResult FamilyMemberUpdate(int id, string relationship, string FamilyName, string FamilyMobile, string FamilyAddress, string Gender, string IDCardNo, System.Nullable<bool> isDefault)
        {
            var returnid = _orderBll.FamilyMemberUpdate(id, relationship, FamilyName, FamilyMobile, FamilyAddress, Gender, IDCardNo, isDefault);
            return Json(returnid, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除指定ID的就诊人
        /// </summary>
        /// <param name="id">就诊人ID</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult FamilyMemberDelete(int id)
        {
            var returnid = _orderBll.FamilyMemberDelete(id);
            return Json(returnid, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 设置指定的就诊人为默认就诊人
        /// </summary>
        /// <param name="id">就诊人ID</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult FamilyMemberSetDefault(int id)
        {
            var returnid = _orderBll.FamilyMemberSetDefault(id);
            return Json(returnid, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="regUser"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetValidateCode(FamilyMemberListModel regUser)
        {
            if (!string.IsNullOrEmpty(regUser.FamilyMobile))
            {
                Random ran = new Random();
                int RandKey = ran.Next(100000, 999999);
                Session["ValidationCode"] = RandKey;
                Session["ValidationCodeGenerateTime"] = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                UserBll usersSevice = new UserBll();
                var validationCode = Convert.ToInt32(Session["ValidationCode"]) ;
                usersSevice.SendMessage(regUser.FamilyMobile, Session["ValidationCode"].ToString());
                return Json(new ReturnCode(validationCode, "验证码已发送，请注意查收!"), JsonRequestBehavior.AllowGet);
            }
            return Json(new ReturnCode(-1, "获取验证码失败，请重试"), JsonRequestBehavior.AllowGet);

        }

        /// <summary>
        /// 预约排班查询接口
        /// </summary>
        /// <param name="startime">开始时间</param>
        /// <param name="endtime">结束时间</param>
        /// <param name="week">周几</param>
        /// <param name="mz_id">门诊ID</param>
        /// <param name="mz_type_id">门诊类型ID</param>
        /// <param name="doctored">医生Id</param>
        /// <param name="org_id">机构ID</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetResSchedulingList(string startime, string week, int mz_id, string mz_type_id, int doctored, int org_id)
        {
            DateTime startimedt = new DateTime();
            DateTime endtimedt = new DateTime();
            if (!string.IsNullOrWhiteSpace(startime) && startime != "请选择日期")
            {
                startimedt = Convert.ToDateTime(startime);
                endtimedt = startimedt.AddDays(1);
            }

            var returnid = _orderBll.GetResSchedulingList(startimedt, endtimedt, week, mz_id, mz_type_id, doctored, org_id);
            return Json(returnid, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetDoctorScheduleBydocID(int docID)
        {
            List<string> returndates = new List<string>();
            var returnvalue = _orderBll.GetDoctorScheduleBydocID(docID);
            if (returnvalue != null && returnvalue.Data.Count() > 0)
            {
                var dates = returnvalue.Data;
                foreach (var item in dates)
                {
                    //string[] Day = new string[] { " 星期日", " 星期一", " 星期二", " 星期三", " 星期四", " 星期五", " 星期六" };
                    //string week = Day[Convert.ToInt32(item.Date.DayOfWeek.ToString("d"))].ToString();
                    returndates.Add(item.Date.ToString("yyyy-MM-dd"));
                }
            }
            return Json(returndates, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取医生排班信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="startime"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetDoctorSchedulingList(int id, string startime)
        {
            DateTime startimedt = new DateTime();
            DateTime endtimedt = new DateTime();
            if (!string.IsNullOrWhiteSpace(startime) && startime != "请选择日期")
            {
                startimedt = Convert.ToDateTime(startime);
                endtimedt = startimedt;
            }
            List<RecentVisitExpertsViewModel> recentVisitExpertsViewModelList = new List<RecentVisitExpertsViewModel>();

            List<Models.SubDate> subDateList = new List<Models.SubDate>();
            var doctorOnTimeInfos = _docInfoBll.GetDoctorScheduleByDate(id, startimedt, endtimedt);
            if (doctorOnTimeInfos.Count > 0)
            {
                foreach (var item in doctorOnTimeInfos)
                {
                    RecentVisitExpertsViewModel recentVisitExpertsViewModel = new RecentVisitExpertsViewModel();
                    recentVisitExpertsViewModel.ClinicID = item.clinicID;
                    recentVisitExpertsViewModel.ClinicinfoID = item.clinicinfoID;
                    recentVisitExpertsViewModel.IsRemote = item.IsRemote;
                    recentVisitExpertsViewModel.Id = item.docID.ToString();
                    recentVisitExpertsViewModel.HospitalID = item.hospitalID;

                    subDateList = item.subdate.Select(m => new Models.SubDate()
                    {
                        Time = m.Time,
                        TimeTarget = m.TimeTarget,
                        Appointment = m.appointment,
                        Capacity = m.capacity,
                        NoBooking = (m.capacity - m.appointment > 0) && CheckBooking(m.capacity, m.appointment, m.Time, startime)
                    }).ToList();
                    recentVisitExpertsViewModel.subdate = subDateList;
                    recentVisitExpertsViewModelList.Add(recentVisitExpertsViewModel);
                }
            }
            return Json(recentVisitExpertsViewModelList, JsonRequestBehavior.AllowGet);
        }

        private bool CheckBooking(int capacity, int appointment, string time,string startime)
        {
            var nobooking = true;
            bool checktwo = true;
            bool checkone = capacity - appointment <= 0;

            var checktime = time.Split('-');
            if (checktime.Length > 0)
            {
                DateTime currentDateTime = DateTime.Now;
                var checkdate = currentDateTime.ToString("yyyy-MM-dd") + " " + checktime[0];
                if (currentDateTime.ToString("yyyy-MM-dd") != startime)
                {
                    checktwo = false;
                }
                else if (!string.IsNullOrWhiteSpace(checkdate))
                {
                    if (currentDateTime.CompareTo(Convert.ToDateTime(checkdate)) < 0)
                    {
                        checktwo = false;
                    }
                }
            }

            if (!checktwo)
            {
                nobooking = checkone;
            }

            return nobooking;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadImage(object data)
        {
            string byteStr = data.ToString();//data:image/jpg;base64,         
            int delLength = byteStr.IndexOf(',') + 1;
            string str = byteStr.Substring(delLength, byteStr.Length - delLength);

            List<string> stringarr = new List<string>();

            Image returnImage = Base64StringToImage(str);
            var serviceurl = Request.Url.Scheme + "://" + Request.Url.Authority;
            var targetName = Guid.NewGuid() + ".jpg";
            var localsrc = serviceurl + "/UploadImage/OrderImage/" + targetName;
            var src = Server.MapPath("/UploadImage/OrderImage/") + targetName;
            returnImage.Save(src,
                System.Drawing.Imaging.ImageFormat.Jpeg);

            stringarr.Add(localsrc);

            return Json(stringarr, JsonRequestBehavior.AllowGet);
        }

        private Image Base64StringToImage(string txt)
        {
            byte[] arr = Convert.FromBase64String(txt);
            MemoryStream ms = new MemoryStream(arr);
            Bitmap bmp = new Bitmap(ms);
            return bmp;
        }

        /// <summary>
        /// 创建预约意向单
        /// </summary>
        /// <param name="pid">就诊人PID （如果没有，传0，但此时必须传一个正确的userInfoJson；否则userInfoJson应传空）</param>
        /// <param name="type">预约类型 普通预约 = 0；加号预约 = 1；点诊 = 2;</param>
        /// <param name="hospId">医院Id</param>
        /// <param name="remoteHospId">医生出诊医院Id 可以判断是否是远程就诊</param>
        /// <param name="depId">门诊Id</param>
        /// <param name="depTypeId">门诊类型Id</param>
        /// <param name="doctorId">医生Id</param>
        /// <param name="timePeriod">预约时间段 使用从接口中取到的开始结束时间，用-连接，如：9:00-10:00</param>
        /// <param name="resvDate">预约日期</param>
        /// <param name="description">客人主诉</param>
        /// <param name="pictures">客户上传的描述图片 多张的话逗号隔开</param>
        /// <param name="userIP">用户下单时候的IP</param>
        /// <param name="platform">平台 Android APP/iOS/微信/Web</param>
        /// <param name="OpenId"></param>
        /// <param name="userInfoJson">用户信息JSON 包括Name(string)，Mobile(string)，Sex(string)，CertNo(string)，Birthday(DateTime?)</param>
        /// <param name="operatorPid">预约操作人PID 当前登陆人的PID（APP没有PID的话传0）</param>
        /// <returns>Data 预约单号</returns>
        [HttpPost]
        public JsonResult ResvIntentionAdd(int pid,
            int type,
            int hospId,
            int remoteHospId,
            int depId,
            int depTypeId,
            int doctorId,
            string timePeriod,
            string resvDate,
            string description,
            string[] pictures,
            string userIP,
            string platform,
            string OpenId,
            string userInfoJson,
            string idCardNo)
        {
            //int iPid = 8254006;
            var operatorPid = Session["pid"] != null ? int.Parse(Session["pid"].ToString()) : 0;

            DateTime resvDateTemp = string.IsNullOrWhiteSpace(resvDate) ? DateTime.Now : Convert.ToDateTime(resvDate);
            var picture = pictures != null && pictures.Length > 0 ? string.Join(",", pictures) : "";
            var issavedimage = true;
            if (!string.IsNullOrWhiteSpace(picture))
            {
                issavedimage = _orderBll.addSeekDetail(pid, picture, "", 2, "Web");
            }

            if (!string.IsNullOrWhiteSpace(idCardNo))
            {
                userInfoJson = userInfoJson.Replace("NoBirthday", CoventBirthday(idCardNo));
                userInfoJson = userInfoJson.Replace("NoSex", CoventSex(idCardNo));
            }

            var returnvalue = _orderBll.ResvIntentionAdd(pid, type, hospId, remoteHospId, depId, depTypeId, doctorId,
                timePeriod, resvDateTemp, description, picture, userIP, platform, OpenId, userInfoJson, operatorPid);
            return Json(returnvalue, JsonRequestBehavior.AllowGet);
        }

        private string CoventBirthday(string IDCardNo)
        {
            var birthday = "";
            if (!string.IsNullOrWhiteSpace(IDCardNo))
            {
                string Sub_str = IDCardNo.Substring(6, 8).Insert(4, "-").Insert(7, "-");   //提取出生年份
                DateTime birdate = new DateTime();
                if (DateTime.TryParse(Sub_str, out birdate))
                {
                    birthday = Convert.ToDateTime(Sub_str).ToString();
                }
            }
            return birthday;
        }

        private string CoventSex(string IDCardNo)
        {
            string rtn;
            string tmp = "";
            if (IDCardNo.Length == 15)
            {
                tmp = IDCardNo.Substring(IDCardNo.Length - 3);
            }
            else if (IDCardNo.Length == 18)
            {
                tmp = IDCardNo.Substring(IDCardNo.Length - 4);
                tmp = tmp.Substring(0, 3);
            }
            int sx = int.Parse(tmp);
            int outNum;
            Math.DivRem(sx, 2, out outNum);
            if (outNum == 0)
            {
                rtn = "女";
            }
            else
            {
                rtn = "男";
            }
            return rtn;
        }

        #endregion

        #region 快速预约

        [HttpPost]
        public JsonResult ResvIntentionQuickAdd(string username, string usermobile, string docname)
        {
            var content = "快速预约，预约人姓名：" + username + ";预约人手机号：" + usermobile + ";预约专家名称：" + docname;
            _orderBll.ResvIntentionQuickAdd(content);
            var returnid = "快速预约成功";

            return Json(returnid, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 提交建议

        [HttpPost]
        public JsonResult SuggestQuickAdd(string suggestcomments, string suggesttername, string suggesttermobile)
        {
            var pid = Session["pid"] != null ? int.Parse(Session["pid"].ToString()) : 0;

            _orderBll.SuggestQuickSend(suggesttername, suggesttermobile, suggestcomments, pid);
            var returnvalue = "建议提交成功";
            return Json(returnvalue, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}